<template>
  <div class="business-list">
    <h2 class="page-title">商机列表</h2>
    
    <!-- 搜索区域 -->
    <div class="search-section">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="商机ID" style="margin-right: 10px;">
          <el-input v-model="searchForm.id" placeholder="请输入商机ID" style="width: 120px;"></el-input>
        </el-form-item>
        <el-form-item label="客户姓名" style="margin-right: 10px;">
          <el-input v-model="searchForm.name" placeholder="请输入客户姓名" style="width: 150px;"></el-input>
        </el-form-item>
        <el-form-item label="手机号" style="margin-right: 10px;">
          <el-input v-model="searchForm.phone" placeholder="请输入手机号" style="width: 150px;"></el-input>
        </el-form-item>
        <el-form-item label="商机状态" style="margin-right: 10px;">
          <el-select v-model="searchForm.status" placeholder="请选择" style="width: 120px;">
            <el-option label="全部" :value="''"></el-option>
            <el-option v-for="(item, index) in statusOptions" :key="index" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="归属人" style="margin-right: 10px;">
          <el-input v-model="searchForm.userId" placeholder="请输入归属人" style="width: 150px;"></el-input>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleSearch" style="text-align: left;">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetForm" style="text-align: left;">重置</el-button>
          </el-form-item>
      </el-form>
    </div>
    
    <!-- 新建商机按钮 -->
    <div class="operation-bar">
        <el-button type="primary" icon="el-icon-plus" @click="handleAddBusiness" style="text-align: left;">新建商机</el-button>
        <el-button v-if="isAdmin" type="warning" icon="el-icon-remove" @click="handleBatchBackToPool" :disabled="selectedIds.length === 0" style="text-align: left;">批量踢回公海</el-button>
      </div>
    
    <!-- 数据表格 -->
    <div class="table-section">
      <el-table
        v-loading="loading"
        :data="businessList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column type="selection" width="55" v-if="isAdmin" />
        <el-table-column prop="id" label="商机ID" width="80" />
        <el-table-column prop="name" label="客户姓名" width="120" />
        <el-table-column prop="phone" label="手机号" width="150" />
        <el-table-column prop="subject" label="意向学科" width="150">
          <template #default="scope">
            {{ getSubjectName(scope.row.subject) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ getStatusLabel(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="userId" label="负责人" width="120">
          <template #default="scope">
            {{ getUserNameById(scope.row.userId) }}
          </template>
        </el-table-column>
        <el-table-column prop="nextTime" label="下次跟进时间" width="180">
          <template #default="scope">
            {{ scope.row.nextTime ? formatDate(scope.row.nextTime) : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150" />
        <el-table-column label="操作" min-width="200" fixed="right">
          <template #default="scope">
            <div class="operation-buttons">
            <!-- 管理员显示分配按钮，但只有当商机负责人为空且状态为1（待分配）时才显示 -->
            <el-button
              v-if="isAdmin && !scope.row.userId && scope.row.status === 1"
              type="primary"
              size="small"
              @click="showAssignDialog(scope.row.id)"
            >
              分配
            </el-button>
            <!-- 业务操作员显示踢回公海按钮，但只有当商机归属人是当前用户且状态为2或3时才显示 -->
            <el-button
              v-else-if="isBusinessOperator && scope.row.userId === currentUserId && (scope.row.status === 2 || scope.row.status === 3)"
              type="warning"
              size="small"
              @click="handleBackToPool(scope.row.id)"
            >
              公海
            </el-button>
            <!-- 业务操作员显示转客户按钮，但只有当商机归属人是当前用户且状态为2（跟进中）时才显示 -->
            <el-button
              v-if="isBusinessOperator && scope.row.userId === currentUserId && scope.row.status === 2"
              type="success"
              size="small"
              @click="handleToCustomer(scope.row.id)"
            >
              客户
            </el-button>
            <!-- 业务操作员显示跟进按钮，但只有当商机归属人是当前用户且状态为2（待跟进）或3（跟进中）时才显示 -->
            <el-button
              v-if="isBusinessOperator && scope.row.userId === currentUserId && (scope.row.status === 2 || scope.row.status === 3)"
              type="info"
              size="small"
              @click="showFollowDialog(scope.row.id)"
            >
              跟进
            </el-button>
          </div>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </div>
    
    <!-- 分配对话框 -->
    <el-dialog
      v-model="assignDialogVisible"
      title="分配商机"
      width="30%"
    >
      <el-form label-position="top">
        <el-form-item label="选择负责人">
          <el-select v-model="selectedUserId" placeholder="请选择负责人">
            <el-option
              v-for="user in userList"
              :key="user.id"
              :label="user.name"
              :value="user.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="assignDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAssign">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 跟进对话框 -->
    <el-dialog
      v-model="followDialogVisible"
      :title="dialogTitle"
      width="60%"
    >
      <div class="follow-dialog-content" style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Helvetica Neue', Arial, sans-serif; font-size: 14px; line-height: 1.6; color: #333;">
        <!-- 基本信息 -->
        <el-form label-position="top" size="small">
          <div class="form-row">
            <el-form-item label="*手机号">
              <el-input :model-value="currentBusinessDetail?.phone" disabled />
            </el-form-item>
            <el-form-item label="*客户姓名">
              <el-input :model-value="currentBusinessDetail?.name" disabled />
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="性别">
              <el-select v-model="currentBusinessDetail.gender">
                <el-option label="男" :value="1" />
                <el-option label="女" :value="2" />
              </el-select>
            </el-form-item>
            <el-form-item label="年龄">
              <el-input v-model="currentBusinessDetail.age" />
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="微信号">
              <el-input v-model="currentBusinessDetail.wechat" />
            </el-form-item>
            <el-form-item label="QQ">
              <el-input v-model="currentBusinessDetail.qq" />
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="意向学科">
              <el-select v-model="currentBusinessDetail.subject">
                <el-option v-for="option in subjectOptions" :key="option.value" :label="option.label" :value="option.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="意向课程">
              <el-select v-model="currentBusinessDetail.courseId">
                <el-option label="课程1" :value="1" />
                <el-option label="课程2" :value="2" />
                <el-option label="课程3" :value="3" />
              </el-select>
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="学历">
              <el-select v-model="currentBusinessDetail.degree">
                <el-option label="高中" :value="1" />
                <el-option label="本科" :value="2" />
                <el-option label="硕士" :value="3" />
                <el-option label="博士" :value="4" />
              </el-select>
            </el-form-item>
            <el-form-item label="在职状态">
              <el-select v-model="currentBusinessDetail.jobStatus">
                <el-option label="在职" :value="1" />
                <el-option label="离职" :value="2" />
                <el-option label="学生" :value="3" />
              </el-select>
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="渠道来源">
              <el-select v-model="currentBusinessDetail.channel">
                <el-option label="线上活动" :value="1" />
                <el-option label="线下推广" :value="2" />
                <el-option label="朋友介绍" :value="3" />
                <el-option label="其他" :value="4" />
              </el-select>
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="currentBusinessDetail.remark" type="textarea" />
            </el-form-item>
          </div>
        </el-form>
        
        <el-divider>跟进信息</el-divider>
        
        <!-- 跟进表单 -->
        <el-form label-position="top" size="small">
          <div class="form-row">
            <el-form-item label="跟进状态" required>
              <el-select v-model="followForm.trackStatus" placeholder="请选择">
                <el-option label="待跟进" :value="1" />
                <el-option label="已跟进" :value="2" />
                <el-option label="意向明确" :value="3" />
                <el-option label="暂无意向" :value="4" />
              </el-select>
            </el-form-item>
            <el-form-item label="沟通重点">
              <el-select v-model="followForm.keyItems" placeholder="请选择(支持多选)" multiple>
                <el-option label="课程" :value="'课程'" />
                <el-option label="价格" :value="'价格'" />
                <el-option label="位置" :value="'位置'" />
                <el-option label="时间" :value="'时间'" />
                <el-option label="师资" :value="'师资'" />
                <el-option label="项目" :value="'项目'" />
                <el-option label="薪资" :value="'薪资'" />
              </el-select>
            </el-form-item>
          </div>
          
          <div class="form-row">
            <el-form-item label="下次跟进">
              <el-date-picker
                v-model="followForm.nextTime"
                type="datetime"
                placeholder="请选择下次跟进时间"
              />
            </el-form-item>
            <el-form-item label="沟通纪要">
              <el-input v-model="followForm.record" placeholder="请输入跟进记录,50字以内" maxlength="50" show-word-limit />
            </el-form-item>
          </div>
        </el-form>
        
        <el-divider>跟进历史</el-divider>
        
        <!-- 跟进历史 -->
        <div class="track-records">
          <el-table :data="trackRecords" border size="small">
            <el-table-column prop="createTime" label="跟进时间" width="150">
              <template #default="scope">
                {{ formatDate(scope.row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="keyItems" label="沟通重点" width="120">
              <template #default="scope">
                {{ formatKeyItems(scope.row.keyItems) }}
              </template>
            </el-table-column>
            <el-table-column prop="trackStatus" label="跟进状态" width="100">
              <template #default="scope">
                {{ getTrackStatusLabel(scope.row.trackStatus) }}
              </template>
            </el-table-column>
            <el-table-column prop="nextTime" label="下次跟进时间" width="150">
              <template #default="scope">
                {{ scope.row.nextTime ? formatDate(scope.row.nextTime) : '-' }}
              </template>
            </el-table-column>
            <el-table-column prop="record" label="沟通纪要" min-width="200" />
            <el-table-column prop="assignName" label="跟进人" width="100" />
          </el-table>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="followDialogVisible = false">关闭</el-button>
            <el-button type="primary" @click="handleSaveFollow">保存跟进</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
import { getBusinessListApi, getBusinessDetailApi, assignBusinessApi, backToPoolApi, toCustomerApi, trackBusinessApi } from '@/api/business'
import { getUsersByDeptApi, getUsersApi, getUsersByRoleApi } from '@/api/user'

// 用户列表
const userList = ref([])

// 判断是否为管理员
const isAdmin = computed(() => {
  try {
    const userInfoStr = localStorage.getItem('userInfo')
    if (userInfoStr) {
      const userInfo = JSON.parse(userInfoStr)
      // 使用roleLabel字段判断管理员，值为'admin'表示管理员
      return userInfo.roleLabel === 'admin'
    }
    return false
  } catch (error) {
    console.error('获取用户信息失败:', error)
    return false
  }
})

// 判断是否为业务操作员（business_operator角色）
const isBusinessOperator = computed(() => {
  try {
    const userInfoStr = localStorage.getItem('userInfo')
    if (userInfoStr) {
      const userInfo = JSON.parse(userInfoStr)
      // roleLabel值为'business_operator'表示业务操作员
      return userInfo.roleLabel === 'business_operator'
    }
    return false
  } catch (error) {
    console.error('获取用户信息失败:', error)
    return false
  }
})

// 获取当前登录用户ID
const currentUserId = computed(() => {
  try {
    const userInfoStr = localStorage.getItem('userInfo')
    if (userInfoStr) {
      const userInfo = JSON.parse(userInfoStr)
      return userInfo.id
    }
    return null
  } catch (error) {
    console.error('获取用户信息失败:', error)
    return null
  }
})

// 加载中状态
const loading = ref(false)

// 商机列表数据
const businessList = ref([])

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 搜索表单
const searchForm = reactive({
  name: '',
  phone: '',
  subject: '',
  status: '',
  userId: ''
})

// 意向学科选项
const subjectOptions = [
  { label: 'Java', value: 1 },
  { label: 'Python', value: 2 },
  { label: '前端', value: 3 },
  { label: '测试', value: 4 },
  { label: '大数据', value: 5 },
  { label: 'AI智能应用开发', value: 6 }
]

// 状态选项
const statusOptions = [
  { label: '待分配', value: 1 },
  { label: '待跟进', value: 2 },
  { label: '跟进中', value: 3 },
  { label: '已回收', value: 4 },
  { label: '已转客户', value: 5 }
]

// 选中的ID数组（用于批量操作）
const selectedIds = ref([])

// 分配对话框
const assignDialogVisible = ref(false)
const selectedUserId = ref('')
const targetBusinessId = ref(null)

// 跟进相关状态
const followDialogVisible = ref(false)
const currentBusinessDetail = ref({})
const trackRecords = ref([])

// 对话框标题计算属性
const dialogTitle = computed(() => {
  return `跟进商机(商机ID: ${currentBusinessDetail.value?.id || ''})`
})

// 跟进表单
const followForm = reactive({
  trackStatus: '',
  keyItems: [],
  nextTime: null,
  record: ''
})

// 获取状态标签
const getStatusLabel = (status) => {
  const option = statusOptions.find(item => item.value === status)
  return option ? option.label : '未知'
}

// 获取状态类型（用于标签样式）
const getStatusType = (status) => {
  switch (status) {
    case 1: return 'warning'
    case 2: return 'warning'
    case 3: return 'success'
    case 4: return 'danger'
    case 5: return 'primary'
    default: return 'default'
  }
}

// 获取意向学科名称
const getSubjectName = (subject) => {
  const option = subjectOptions.find(item => item.value === subject)
  return option ? option.label : '未知'
}

// 根据用户ID获取用户姓名
const getUserNameById = (userId) => {
  const user = userList.value.find(item => item.id === userId)
  return user ? user.name : '未分配'
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 格式化沟通重点
const formatKeyItems = (keyItems) => {
  try {
    // 处理可能的JSON字符串
    if (typeof keyItems === 'string') {
      const parsed = JSON.parse(keyItems)
      if (Array.isArray(parsed)) {
        return parsed.join(', ')
      }
      return keyItems
    }
    // 直接处理数组
    if (Array.isArray(keyItems)) {
      return keyItems.join(', ')
    }
    return keyItems || ''
  } catch (error) {
    return keyItems || ''
  }
}

// 获取跟进状态标签
const getTrackStatusLabel = (status) => {
  const statusMap = {
    1: '待跟进',
    2: '已跟进',
    3: '意向明确',
    4: '暂无意向'
  }
  return statusMap[status] || ''
}

// 加载用户列表
const loadUserList = async () => {
  try {
    // 优先使用根据角色标签获取用户列表的方式，获取业务操作员角色的用户
    let response = await getUsersByRoleApi('business_operator')
    
    // 如果按角色获取失败或数据为空，尝试按部门获取
    if (!response || response.code !== 1 || !response.data || response.data.length === 0) {
      console.log('按角色获取用户列表失败或为空，尝试按部门获取')
      response = await getUsersByDeptApi(2) // 假设部门ID为2是业务部
    }
    
    // 如果按部门获取也失败，尝试获取所有用户列表
    if (!response || response.code !== 1 || !response.data || response.data.length === 0) {
      console.log('按部门获取用户列表失败或为空，尝试获取所有用户')
      response = await getUsersApi()
    }
    
    if (response && response.code === 1) {
      userList.value = response.data || []
      console.log('用户列表加载成功，共', userList.value.length, '个用户')
    } else {
      console.error('获取用户列表失败:', response?.msg || '未知错误')
    }
  } catch (error) {
    console.error('加载用户列表异常:', error)
    // 异常情况下，尝试降级方案
    try {
      const fallbackResponse = await getUsersApi()
      if (fallbackResponse && fallbackResponse.code === 1) {
        userList.value = fallbackResponse.data || []
        console.log('降级方案：获取所有用户列表成功')
      }
    } catch (fallbackError) {
      console.error('降级方案也失败:', fallbackError)
    }
  }
}

// 加载商机列表
const loadBusinessList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    const response = await getBusinessListApi(params)
    if (response.code === 1) {
      businessList.value = response.data.rows || []
      pagination.total = response.data.total || 0
    } else {
      ElMessage.error(response.msg || '加载失败')
    }
  } catch (error) {
    console.error('加载商机列表失败:', error)
    ElMessage.error('加载失败')
  } finally {
    loading.value = false
  }
}

// 显示分配对话框
const showAssignDialog = (businessId) => {
  targetBusinessId.value = businessId
  selectedUserId.value = ''
  assignDialogVisible.value = true
}

// 处理分配
const handleAssign = async () => {
  if (!selectedUserId.value) {
    ElMessage.warning('请选择负责人')
    return
  }
  
  try {
    const response = await assignBusinessApi(targetBusinessId.value, selectedUserId.value)
    if (response.code === 1) {
      ElMessage.success('分配成功')
      assignDialogVisible.value = false
      loadBusinessList()
    } else {
      ElMessage.error(response.msg || '分配失败')
    }
  } catch (error) {
    console.error('分配失败:', error)
    ElMessage.error('分配失败')
  }
}

// 处理踢回公海
const handleBackToPool = async (businessId) => {
  try {
    await ElMessageBox.confirm('确定要将该商机踢回公海吗？', '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await backToPoolApi(businessId)
    if (response.code === 1) {
      ElMessage.success('踢回成功')
      loadBusinessList()
    } else {
      ElMessage.error(response.msg || '踢回失败')
    }
  } catch (error) {
    if (error.message !== 'cancel') {
      console.error('踢回失败:', error)
      ElMessage.error('踢回失败')
    }
  }
}

// 处理批量踢回公海
const handleBatchBackToPool = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要踢回公海的商机')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要将选中的${selectedIds.value.length}个商机踢回公海吗？`, '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    for (const businessId of selectedIds.value) {
      const response = await backToPoolApi(businessId)
      if (response.code !== 1) {
        throw new Error(response.msg || '踢回失败')
      }
    }
    
    ElMessage.success('批量踢回成功')
    selectedIds.value = []
    loadBusinessList()
  } catch (error) {
    if (error.message !== 'cancel') {
      console.error('批量踢回失败:', error)
      ElMessage.error(error.message || '批量踢回失败')
    }
  }
}

// 处理转客户
const handleToCustomer = async (businessId) => {
  try {
    await ElMessageBox.confirm('确定要将该商机转为客户吗？', '确认操作', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await toCustomerApi(businessId)
    if (response.code === 1) {
      ElMessage.success('转客户成功')
      loadBusinessList()
    } else {
      ElMessage.error(response.msg || '转客户失败')
    }
  } catch (error) {
    if (error.message !== 'cancel') {
      console.error('转客户失败:', error)
      ElMessage.error('转客户失败')
    }
  }
}

// 显示跟进对话框
const showFollowDialog = async (businessId) => {
  try {
    // 重置表单
    Object.assign(followForm, {
      trackStatus: '',
      keyItems: [],
      nextTime: null,
      record: ''
    })
    
    // 获取商机详情
    const response = await getBusinessDetailApi(businessId)
    if (response.code === 1) {
      currentBusinessDetail.value = response.data
      trackRecords.value = response.data.trackRecords || []
      followDialogVisible.value = true
    } else {
      ElMessage.error(response.msg || '获取商机详情失败')
    }
  } catch (error) {
    console.error('获取商机详情失败:', error)
    ElMessage.error('获取商机详情失败')
  }
}

// 保存跟进信息
const handleSaveFollow = async () => {
  try {
    // 验证必填字段
    if (!followForm.trackStatus) {
      ElMessage.warning('请选择跟进状态')
      return
    }
    
    // 构建请求数据 - 确保keyItems以集合形式发送，内部为选择的内容string形式
    const requestData = {
      id: currentBusinessDetail.value.id,
      name: currentBusinessDetail.value.name,
      phone: currentBusinessDetail.value.phone,
      gender: currentBusinessDetail.value.gender,
      age: currentBusinessDetail.value.age,
      wechat: currentBusinessDetail.value.wechat,
      qq: currentBusinessDetail.value.qq,
      subject: currentBusinessDetail.value.subject,
      courseId: currentBusinessDetail.value.courseId,
      degree: currentBusinessDetail.value.degree,
      jobStatus: currentBusinessDetail.value.jobStatus,
      channel: currentBusinessDetail.value.channel,
      remark: currentBusinessDetail.value.remark,
      status: currentBusinessDetail.value.status,
      userId: currentBusinessDetail.value.userId,
      clueId: currentBusinessDetail.value.clueId,
      nextTime: followForm.nextTime ? new Date(followForm.nextTime).toISOString() : null,
      keyItems: followForm.keyItems || [], // 确保是数组格式
      trackStatus: followForm.trackStatus,
      record: followForm.record
    }
    
    // 调用跟进商机API
    const response = await trackBusinessApi(requestData)
    if (response.code === 1) {
      ElMessage.success('跟进成功')
      followDialogVisible.value = false
      loadBusinessList() // 重新加载商机列表
    } else {
      ElMessage.error(response.msg || '跟进失败')
    }
  } catch (error) {
    console.error('跟进失败:', error)
    ElMessage.error('跟进失败，请稍后重试')
  }
}

// 新建商机
const handleAddBusiness = () => {
  // 跳转到新建商机页面
  router.push('/business/add')
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  loadBusinessList()
}

// 重置表单
const resetForm = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  loadBusinessList()
}

// 当前页变化
const handlePageChange = (current) => {
  pagination.currentPage = current
  loadBusinessList()
}

// 初始化
onMounted(() => {
  loadUserList()
  loadBusinessList()
})
</script>

<style scoped>
.business-list {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
}

.search-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.search-form .el-form-item {
  margin-bottom: 0;
}

.operation-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 12px;
}

.table-section {
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 操作按钮容器样式 */
.operation-buttons {
  display: flex;
  gap: 6px;
  padding: 4px;
}

/* Element Plus按钮美化 */
:deep(.el-button) {
  transition: all 0.3s ease;
  border-radius: 8px;
}

:deep(.el-button:hover) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 主要按钮样式 */
:deep(.el-button--primary) {
  background-color: #409eff;
  border-color: #409eff;
}

:deep(.el-button--primary:hover) {
  background-color: #66b1ff;
  border-color: #66b1ff;
  box-shadow: 0 4px 12px rgba(64, 169, 255, 0.3);
}

/* 警告按钮样式 */
:deep(.el-button--warning) {
  background-color: #e6a23c;
  border-color: #e6a23c;
}

:deep(.el-button--warning:hover) {
  background-color: #ebb563;
  border-color: #ebb563;
  box-shadow: 0 4px 12px rgba(230, 162, 60, 0.3);
}

/* 成功按钮样式 */
:deep(.el-button--success) {
  background-color: #67c23a;
  border-color: #67c23a;
}

:deep(.el-button--success:hover) {
  background-color: #85ce61;
  border-color: #85ce61;
  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
}

/* 信息按钮样式 */
:deep(.el-button--info) {
  background-color: #909399;
  border-color: #909399;
  color: white;
}

:deep(.el-button--info:hover) {
  background-color: #a6a9ad;
  border-color: #a6a9ad;
  box-shadow: 0 4px 12px rgba(144, 147, 153, 0.3);
}

/* 表格内操作按钮样式优化 */
:deep(.el-table .el-button) {
  margin: 0 2px;
  padding: 4px 10px;
  min-width: 50px;
  font-size: 12px;
}

/* 按钮悬停效果 */
:deep(.el-table .el-button:hover) {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

/* 响应式调整 */
@media (max-width: 768px) {
  :deep(.el-button) {
    font-size: 12px;
    padding: 6px 12px;
  }
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  text-align: right;
}

.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
}

.form-row .el-form-item {
  flex: 1;
  margin-bottom: 0;
}

.follow-dialog-content {
  max-height: 600px;
  overflow-y: auto;
}

/* 响应式设计优化 */
@media (max-width: 1400px) {
  .search-form {
    gap: 16px;
  }
  
  .search-form .el-input,
  .search-form .el-select {
    width: 170px;
  }
  
  .search-form .el-button,
  .operation-bar .el-button {
    padding: 8px 16px;
    font-size: 13px;
  }
}

@media (max-width: 1200px) {
  .search-form {
    justify-content: flex-start;
  }
  
  .search-form .el-form-item:last-child {
    margin-left: 0;
    margin-top: 16px;
    width: 100%;
    justify-content: flex-start;
    padding-left: 92px;
  }
}

@media (max-width: 768px) {
  .business-list {
    padding: 10px;
  }
  
  .page-title {
    font-size: 18px;
    margin-bottom: 16px;
  }
  
  .search-section {
    padding: 16px;
    margin-bottom: 16px;
  }
  
  .operation-bar {
    margin-bottom: 16px;
  }
  
  .search-form {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }
  
  .search-form .el-form-item {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-form .el-form-item__label {
    width: auto;
    text-align: left;
    margin-bottom: 8px;
    margin-right: 0;
  }
  
  .search-form .el-input,
  .search-form .el-select {
    width: 100%;
  }
  
  .search-form .el-form-item:last-child {
    padding-left: 0;
    margin-top: 8px;
    flex-direction: row;
    justify-content: flex-start;
  }
}
</style>
